let login=document.getElementById('login')
let register=document.getElementById('register')
let form_box=document.getElementsByClassName('form-box')[0]


// register.addEventListener('click',()=>{
//     form_box.style.transform='translateX(80%)'
// })
// login.addEventListener('click',()=>{
//     form_box.style.transform='translateX(0%)'
// })
const openEyes1=document.querySelector('.openEyes1')
const closeEyes1=document.querySelector('.closeEyes1')
const inputPassword0=document.getElementsByClassName('input_password')[0]
openEyes1.addEventListener('click',function(){
    openEyes1.style.display='none'
    closeEyes1.style.display='flex'
    inputPassword0.type='password'
})
closeEyes1.addEventListener('click',function(){
    openEyes1.style.display='flex'
    closeEyes1.style.display='none'
    inputPassword0.type='text'
})

const passwordInput=document.querySelector('.input_password-again')
passwordInput.addEventListener('input',function(){
    const password=document.querySelector('.input_password').value
    const confirmPassword=document.querySelector('.input_password-again').value
    if(password===confirmPassword){
        document.getElementById('resultPasswordAgain').textContent='';
    }else{
        document.getElementById('resultPasswordAgain').textContent='两次输入的密码不一致，请重新输入';
    }
})
const  input_user=document.querySelector(".input_txt1")
input_user.addEventListener('input',validateUser)
function validateUser() {
    var txt1=document.querySelector(".input_txt1").value;
    const regex = /^.{1,20}$/;
    if (regex.test(txt1)) {
        document.getElementById('resultUser').textContent = '';
    } else {
        document.getElementById('resultUser').textContent = '用户名长度需在1到20位之间';
    }
}
function validatePassword() {
    var password=document.querySelector(".input_password").value;
    const regex = /^.{6,64}$/;
    if (regex.test(password)) {
        document.getElementById('resultPassword0').textContent = '';
    } else {
        document.getElementById('resultPassword0').textContent = '密码长度需在 6 到 64 位之间';
    }
}
var inputPassword=document.querySelector('.input_password')
inputPassword.addEventListener('input',validatePassword)

function validateEmail() {
    const  email=document.querySelector(".input_txt").value;
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

    if (emailRegex.test(email)) {
        document.getElementById('resultEmail0').textContent = '';
    } else {
        document.getElementById('resultEmail0').textContent = '邮箱地址无效';
    }
}
const  input_email=document.querySelector(".input_txt")
input_email.addEventListener('input',validateEmail)
const openEyes2=document.querySelector('.openEyes2')
const closeEyes2=document.querySelector('.closeEyes2')

openEyes2.addEventListener('click',function(){
    openEyes2.style.display='none'
    closeEyes2.style.display='flex'

    passwordInput.type='password'
})
closeEyes2.addEventListener('click',function(){
    openEyes2.style.display='flex'
    closeEyes2.style.display='none'

    passwordInput.type='text'
})


function showCustomAlert(message, duration) {
    let customAlert = document.getElementById('customAlert');
    if (!customAlert) {
        div_outter=document.createElement('div');
        customAlert = document.createElement('div');
        customAlert.id = 'customAlert';
        // customAlert.style.margin='7px 12px';
        const alertMessage = document.createElement('p');
        alertMessage.id = 'alertMessage';
        customAlert.appendChild(alertMessage);

        document.body.appendChild(customAlert);
    }

    const alertMessage = document.getElementById('alertMessage');

    alertMessage.textContent = message;
    if(alertMessage.textContent==null){
        customAlert.style.display = 'none';
    }

    customAlert.style.display = 'block';
    setTimeout(() => {
        customAlert.style.display = 'none';
    }, duration);
}
if (errorMessage && errorMessage !== '') {
    showCustomAlert(errorMessage, 3000);
}
//
// const form=document.getElementsByClassName('register-box')[0]
// form.addEventListener('submit',function(event){
//     event.preventDefault()
// })
const input_code=document.getElementsByClassName('input_code')[0]
const registerButton=document.getElementsByClassName('registerButton')[0]
// registerButton.addEventListener('click',function(){
//
//     if(input_email.value.trim()===''){
//         input_email.value='请输入邮箱地址'
//         input_email.style.color='red'
//     }
//     if(inputPassword.value.trim()===''){
//         openEyes1.style.display='flex'
//         closeEyes1.style.display='none'
//         inputPassword.type='text'
//         inputPassword.value='请输入密码'
//         inputPassword.style.color='red'
//     }
//     if(passwordInput.value.trim()===''){
//         openEyes2.style.display='flex'
//         closeEyes2.style.display='none'
//         passwordInput.type='text'
//         passwordInput.value='请再次输入密码'
//         passwordInput.style.color='red'
//     }
//     if(input_user.value.trim()===''){
//         input_user.value='请输入用户名'
//         input_user.style.color='red'
//     }
//     if(input_code.value.trim()===''){
//         input_code.value='不能为空'
//         input_code.style.color='red'
//
//     }
//
// })
function sendCode(email,btn) {

    const filteredEmail=email.replace(/<[^>]*>/g, '')
console.log(btn)


    if(filteredEmail){
        $.ajax({
            url:  '/register/sendCode',
            type: 'POST',
            data: {email: email},
            success: function(result){
                showCustomAlert('获取验证码成功',3000)
                refresh(btn,60);
            },
            error:function(error){
                showCustomAlert('请求出错: ' + error.status + ' ' + error.statusText, 3000);
                console.log(error);
            }

        })
    }else{
        showCustomAlert('邮箱为空，请输入邮箱',3000)
    }

}
inputPassword.addEventListener('focus',function(){

    if(this.value==='请输入密码'){
        this.value=''
        this.style.color='white'

    }
})
input_email.addEventListener('focus',function(){
    if(this.value==='请输入邮箱地址'){
        this.value=''
        this.style.color='white'
    }
})
passwordInput.addEventListener('focus',function(){
    if(this.value==='请再次输入密码'){
        this.value=''
        this.style.color='white'
    }
})
input_user.addEventListener('focus',function(){
    if(this.value==='请输入用户名'){
        this.value=''
        this.style.color='white'
    }
})
input_code.addEventListener('focus',function(){
    if(this.value==='不能为空'){
        this.value=''
        this.style.color='white'
    }

})
function dosubmit(){

    if(input_email.value.trim()===''){
        event.preventDefault();
        input_email.value='请输入邮箱地址'
        input_email.style.color='red'
    }
    if(inputPassword.value.trim()===''){
        event.preventDefault();
        openEyes1.style.display='flex'
        closeEyes1.style.display='none'
        inputPassword.type='text'
        inputPassword.value='请输入密码'
        inputPassword.style.color='red'
    }
    if(passwordInput.value.trim()===''){
        event.preventDefault();
        openEyes2.style.display='flex'
        closeEyes2.style.display='none'
        passwordInput.type='text'
        passwordInput.value='请再次输入密码'
        passwordInput.style.color='red'
    }
    if(input_user.value.trim()===''){
        event.preventDefault();
        input_user.value='请输入用户名'
        input_user.style.color='red'
    }
    if(input_code.value.trim()===''){
        event.preventDefault();
        input_code.value='不能为空'
        input_code.style.color='red'

    }
    if(input_email.value.trim()==='请输入邮箱地址'){
        event.preventDefault();

    }
    if(inputPassword.value.trim()==='请输入密码'){
        event.preventDefault();

    }
    if(passwordInput.value.trim()==='请再次输入密码'){
        event.preventDefault();

    }
    if(input_user.value.trim()==='请输入用户名'){
        event.preventDefault();

    }
    if(input_code.value.trim()==='不能为空'){
        event.preventDefault();


    }
}
//
// function refresh(btn,initialCountdown){
//     let countdown=initialCountdown;
//     let  timer;
// console.log(btn+"refresh")
//     btn.disabled=true;
//     btn.style.pointerEvents = 'none'
//     /*  let time = localStorage.getItem("time"); */
//     console.log(this)
//     btn.textContent=`${countdown}s后重发`
//     timer=setInterval(()=>{
//         countdown--
//         localStorage.setItem("time", countdown)
//         if(countdown>0){
//             btn.textContent=`${countdown}s后重发`
//         }else{
//             localStorage.clear();
//             clearInterval(timer)
//             btn.disabled=false
//             // btn.classList.add('.getCode')
//             btn.textContent=`获取验证码`
//             btn.style.pointerEvents = 'auto'
//         }
//     },1000)
// }
function refresh(btn, initialCountdown) {
    let countdown = initialCountdown;
    let timer;

    btn.disabled = true;
    btn.style.pointerEvents = 'none';
    btn.textContent = `${countdown}s后重发`;

    // 启动定时器前，先存储初始倒计时
    localStorage.setItem("countdown", countdown); // 存储总倒计时时间
    localStorage.setItem("startTime", Date.now()); // 存储开始时间（用于计算剩余时间）

    timer = setInterval(() => {
        // 计算剩余时间（避免因页面切换导致的计时偏差）
        const elapsed = Date.now() - parseInt(localStorage.getItem("startTime"));
        const remaining = countdown - Math.floor(elapsed / 1000);

        if (remaining > 0) {
            localStorage.setItem("countdown", remaining); // 更新剩余时间
            btn.textContent = `${remaining}s后重发`;
        } else {
            localStorage.removeItem("countdown");
            localStorage.removeItem("startTime");
            clearInterval(timer);
            btn.disabled = false;
            btn.textContent = "获取验证码";
            btn.style.pointerEvents = 'auto';
        }
    }, 1000);
}
// document.addEventListener('DOMContentLoaded', function () {
//     let getCode = document.querySelector('.get-code');
//    let btn = getCode;
//     // 页面加载时检查是否有剩余时间
//     let time = localStorage.getItem("time");
//     if (time && parseInt(time) > 0) {
//         refresh(btn, parseInt(time));
//     }
// })
document.addEventListener('DOMContentLoaded', function () {
    const getCodeBtn = document.querySelector('.get-code');

    // 从localStorage获取存储的倒计时状态
    const savedCountdown = localStorage.getItem("countdown");
    const savedStartTime = localStorage.getItem("startTime");

    if (savedCountdown && savedStartTime) {
        // 计算剩余时间
        const elapsed = Date.now() - parseInt(savedStartTime);
        const remaining = parseInt(savedCountdown) - Math.floor(elapsed / 1000);

        if (remaining > 0) {
            // 恢复倒计时
            refresh(getCodeBtn, remaining);
        } else {
            // 清除过期的存储数据
            localStorage.removeItem("countdown");
            localStorage.removeItem("startTime");
        }
    }
});
// 存储时
localStorage.setItem("countdown", String(countdown)); // 转为字符串存储
localStorage.setItem("startTime", String(Date.now())); // 转为字符串存储

// 读取时
const savedCountdown = parseInt(localStorage.getItem("countdown")); // 转为数字
const savedStartTime = parseInt(localStorage.getItem("startTime")); // 转为数字